package_finder.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  1. """Routines related to PyPI, indexes"""
  2. # The following comment should be removed at some point in the future.
  3. # mypy: strict-optional=False
  4. from __future__ import absolute_import
  5. import logging
  6. import re
  7. from pip._vendor.packaging import specifiers
  8. from pip._vendor.packaging.utils import canonicalize_name
  9. from pip._vendor.packaging.version import parse as parse_version
  10. from pip._internal.exceptions import (
  11. BestVersionAlreadyInstalled,
  12. DistributionNotFound,
  13. InvalidWheelFilename,
  14. UnsupportedWheel,
  15. )
  16. from pip._internal.index.collector import parse_links
  17. from pip._internal.models.candidate import InstallationCandidate
  18. from pip._internal.models.format_control import FormatControl
  19. from pip._internal.models.link import Link
  20. from pip._internal.models.selection_prefs import SelectionPreferences
  21. from pip._internal.models.target_python import TargetPython
  22. from pip._internal.models.wheel import Wheel
  23. from pip._internal.utils.filetypes import WHEEL_EXTENSION
  24. from pip._internal.utils.logging import indent_log
  25. from pip._internal.utils.misc import build_netloc
  26. from pip._internal.utils.packaging import check_requires_python
  27. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  28. from pip._internal.utils.unpacking import SUPPORTED_EXTENSIONS
  29. from pip._internal.utils.urls import url_to_path
  30. if MYPY_CHECK_RUNNING:
  31. from typing import (
  32. FrozenSet, Iterable, List, Optional, Set, Text, Tuple, Union,
  33. )
  34. from pip._vendor.packaging.tags import Tag
  35. from pip._vendor.packaging.version import _BaseVersion
  36. from pip._internal.index.collector import LinkCollector
  37. from pip._internal.models.search_scope import SearchScope
  38. from pip._internal.req import InstallRequirement
  39. from pip._internal.utils.hashes import Hashes
  40. BuildTag = Union[Tuple[()], Tuple[int, str]]
  41. CandidateSortingKey = (
  42. Tuple[int, int, int, _BaseVersion, BuildTag, Optional[int]]
  43. )
  44. __all__ = ['FormatControl', 'BestCandidateResult', 'PackageFinder']
  45. logger = logging.getLogger(__name__)
  46. def _check_link_requires_python(
  47. link, # type: Link
  48. version_info, # type: Tuple[int, int, int]
  49. ignore_requires_python=False, # type: bool
  50. ):
  51. # type: (...) -> bool
  52. """
  53. Return whether the given Python version is compatible with a link's
  54. "Requires-Python" value.
  55. :param version_info: A 3-tuple of ints representing the Python
  56. major-minor-micro version to check.
  57. :param ignore_requires_python: Whether to ignore the "Requires-Python"
  58. value if the given Python version isn't compatible.
  59. """
  60. try:
  61. is_compatible = check_requires_python(
  62. link.requires_python, version_info=version_info,
  63. )
  64. except specifiers.InvalidSpecifier:
  65. logger.debug(
  66. "Ignoring invalid Requires-Python (%r) for link: %s",
  67. link.requires_python, link,
  68. )
  69. else:
  70. if not is_compatible:
  71. version = '.'.join(map(str, version_info))
  72. if not ignore_requires_python:
  73. logger.debug(
  74. 'Link requires a different Python (%s not in: %r): %s',
  75. version, link.requires_python, link,
  76. )
  77. return False
  78. logger.debug(
  79. 'Ignoring failed Requires-Python check (%s not in: %r) '
  80. 'for link: %s',
  81. version, link.requires_python, link,
  82. )
  83. return True
  84. class LinkEvaluator(object):
  85. """
  86. Responsible for evaluating links for a particular project.
  87. """
  88. _py_version_re = re.compile(r'-py([123]\.?[0-9]?)$')
  89. # Don't include an allow_yanked default value to make sure each call
  90. # site considers whether yanked releases are allowed. This also causes
  91. # that decision to be made explicit in the calling code, which helps
  92. # people when reading the code.
  93. def __init__(
  94. self,
  95. project_name, # type: str
  96. canonical_name, # type: str
  97. formats, # type: FrozenSet[str]
  98. target_python, # type: TargetPython
  99. allow_yanked, # type: bool
  100. ignore_requires_python=None, # type: Optional[bool]
  101. ):
  102. # type: (...) -> None
  103. """
  104. :param project_name: The user supplied package name.
  105. :param canonical_name: The canonical package name.
  106. :param formats: The formats allowed for this package. Should be a set
  107. with 'binary' or 'source' or both in it.
  108. :param target_python: The target Python interpreter to use when
  109. evaluating link compatibility. This is used, for example, to
  110. check wheel compatibility, as well as when checking the Python
  111. version, e.g. the Python version embedded in a link filename
  112. (or egg fragment) and against an HTML link's optional PEP 503
  113. "data-requires-python" attribute.
  114. :param allow_yanked: Whether files marked as yanked (in the sense
  115. of PEP 592) are permitted to be candidates for install.
  116. :param ignore_requires_python: Whether to ignore incompatible
  117. PEP 503 "data-requires-python" values in HTML links. Defaults
  118. to False.
  119. """
  120. if ignore_requires_python is None:
  121. ignore_requires_python = False
  122. self._allow_yanked = allow_yanked
  123. self._canonical_name = canonical_name
  124. self._ignore_requires_python = ignore_requires_python
  125. self._formats = formats
  126. self._target_python = target_python
  127. self.project_name = project_name
  128. def evaluate_link(self, link):
  129. # type: (Link) -> Tuple[bool, Optional[Text]]
  130. """
  131. Determine whether a link is a candidate for installation.
  132. :return: A tuple (is_candidate, result), where `result` is (1) a
  133. version string if `is_candidate` is True, and (2) if
  134. `is_candidate` is False, an optional string to log the reason
  135. the link fails to qualify.
  136. """
  137. version = None
  138. if link.is_yanked and not self._allow_yanked:
  139. reason = link.yanked_reason or '<none given>'
  140. # Mark this as a unicode string to prevent "UnicodeEncodeError:
  141. # 'ascii' codec can't encode character" in Python 2 when
  142. # the reason contains non-ascii characters.
  143. return (False, u'yanked for reason: {}'.format(reason))
  144. if link.egg_fragment:
  145. egg_info = link.egg_fragment
  146. ext = link.ext
  147. else:
  148. egg_info, ext = link.splitext()
  149. if not ext:
  150. return (False, 'not a file')
  151. if ext not in SUPPORTED_EXTENSIONS:
  152. return (False, 'unsupported archive format: {}'.format(ext))
  153. if "binary" not in self._formats and ext == WHEEL_EXTENSION:
  154. reason = 'No binaries permitted for {}'.format(
  155. self.project_name)
  156. return (False, reason)
  157. if "macosx10" in link.path and ext == '.zip':
  158. return (False, 'macosx10 one')
  159. if ext == WHEEL_EXTENSION:
  160. try:
  161. wheel = Wheel(link.filename)
  162. except InvalidWheelFilename:
  163. return (False, 'invalid wheel filename')
  164. if canonicalize_name(wheel.name) != self._canonical_name:
  165. reason = 'wrong project name (not {})'.format(
  166. self.project_name)
  167. return (False, reason)
  168. supported_tags = self._target_python.get_tags()
  169. if not wheel.supported(supported_tags):
  170. # Include the wheel's tags in the reason string to
  171. # simplify troubleshooting compatibility issues.
  172. file_tags = wheel.get_formatted_file_tags()
  173. reason = (
  174. "none of the wheel's tags match: {}".format(
  175. ', '.join(file_tags)
  176. )
  177. )
  178. return (False, reason)
  179. version = wheel.version
  180. # This should be up by the self.ok_binary check, but see issue 2700.
  181. if "source" not in self._formats and ext != WHEEL_EXTENSION:
  182. reason = 'No sources permitted for {}'.format(self.project_name)
  183. return (False, reason)
  184. if not version:
  185. version = _extract_version_from_fragment(
  186. egg_info, self._canonical_name,
  187. )
  188. if not version:
  189. reason = 'Missing project version for {}'.format(self.project_name)
  190. return (False, reason)
  191. match = self._py_version_re.search(version)
  192. if match:
  193. version = version[:match.start()]
  194. py_version = match.group(1)
  195. if py_version != self._target_python.py_version:
  196. return (False, 'Python version is incorrect')
  197. supports_python = _check_link_requires_python(
  198. link, version_info=self._target_python.py_version_info,
  199. ignore_requires_python=self._ignore_requires_python,
  200. )
  201. if not supports_python:
  202. # Return None for the reason text to suppress calling
  203. # _log_skipped_link().
  204. return (False, None)
  205. logger.debug('Found link %s, version: %s', link, version)
  206. return (True, version)
  207. def filter_unallowed_hashes(
  208. candidates, # type: List[InstallationCandidate]
  209. hashes, # type: Hashes
  210. project_name, # type: str
  211. ):
  212. # type: (...) -> List[InstallationCandidate]
  213. """
  214. Filter out candidates whose hashes aren't allowed, and return a new
  215. list of candidates.
  216. If at least one candidate has an allowed hash, then all candidates with
  217. either an allowed hash or no hash specified are returned. Otherwise,
  218. the given candidates are returned.
  219. Including the candidates with no hash specified when there is a match
  220. allows a warning to be logged if there is a more preferred candidate
  221. with no hash specified. Returning all candidates in the case of no
  222. matches lets pip report the hash of the candidate that would otherwise
  223. have been installed (e.g. permitting the user to more easily update
  224. their requirements file with the desired hash).
  225. """
  226. if not hashes:
  227. logger.debug(
  228. 'Given no hashes to check %s links for project %r: '
  229. 'discarding no candidates',
  230. len(candidates),
  231. project_name,
  232. )
  233. # Make sure we're not returning back the given value.
  234. return list(candidates)
  235. matches_or_no_digest = []
  236. # Collect the non-matches for logging purposes.
  237. non_matches = []
  238. match_count = 0
  239. for candidate in candidates:
  240. link = candidate.link
  241. if not link.has_hash:
  242. pass
  243. elif link.is_hash_allowed(hashes=hashes):
  244. match_count += 1
  245. else:
  246. non_matches.append(candidate)
  247. continue
  248. matches_or_no_digest.append(candidate)
  249. if match_count:
  250. filtered = matches_or_no_digest
  251. else:
  252. # Make sure we're not returning back the given value.
  253. filtered = list(candidates)
  254. if len(filtered) == len(candidates):
  255. discard_message = 'discarding no candidates'
  256. else:
  257. discard_message = 'discarding {} non-matches:\n {}'.format(
  258. len(non_matches),
  259. '\n '.join(str(candidate.link) for candidate in non_matches)
  260. )
  261. logger.debug(
  262. 'Checked %s links for project %r against %s hashes '
  263. '(%s matches, %s no digest): %s',
  264. len(candidates),
  265. project_name,
  266. hashes.digest_count,
  267. match_count,
  268. len(matches_or_no_digest) - match_count,
  269. discard_message
  270. )
  271. return filtered
  272. class CandidatePreferences(object):
  273. """
  274. Encapsulates some of the preferences for filtering and sorting
  275. InstallationCandidate objects.
  276. """
  277. def __init__(
  278. self,
  279. prefer_binary=False, # type: bool
  280. allow_all_prereleases=False, # type: bool
  281. ):
  282. # type: (...) -> None
  283. """
  284. :param allow_all_prereleases: Whether to allow all pre-releases.
  285. """
  286. self.allow_all_prereleases = allow_all_prereleases
  287. self.prefer_binary = prefer_binary
  288. class BestCandidateResult(object):
  289. """A collection of candidates, returned by `PackageFinder.find_best_candidate`.
  290. This class is only intended to be instantiated by CandidateEvaluator's
  291. `compute_best_candidate()` method.
  292. """
  293. def __init__(
  294. self,
  295. candidates, # type: List[InstallationCandidate]
  296. applicable_candidates, # type: List[InstallationCandidate]
  297. best_candidate, # type: Optional[InstallationCandidate]
  298. ):
  299. # type: (...) -> None
  300. """
  301. :param candidates: A sequence of all available candidates found.
  302. :param applicable_candidates: The applicable candidates.
  303. :param best_candidate: The most preferred candidate found, or None
  304. if no applicable candidates were found.
  305. """
  306. assert set(applicable_candidates) <= set(candidates)
  307. if best_candidate is None:
  308. assert not applicable_candidates
  309. else:
  310. assert best_candidate in applicable_candidates
  311. self._applicable_candidates = applicable_candidates
  312. self._candidates = candidates
  313. self.best_candidate = best_candidate
  314. def iter_all(self):
  315. # type: () -> Iterable[InstallationCandidate]
  316. """Iterate through all candidates.
  317. """
  318. return iter(self._candidates)
  319. def iter_applicable(self):
  320. # type: () -> Iterable[InstallationCandidate]
  321. """Iterate through the applicable candidates.
  322. """
  323. return iter(self._applicable_candidates)
  324. class CandidateEvaluator(object):
  325. """
  326. Responsible for filtering and sorting candidates for installation based
  327. on what tags are valid.
  328. """
  329. @classmethod
  330. def create(
  331. cls,
  332. project_name, # type: str
  333. target_python=None, # type: Optional[TargetPython]
  334. prefer_binary=False, # type: bool
  335. allow_all_prereleases=False, # type: bool
  336. specifier=None, # type: Optional[specifiers.BaseSpecifier]
  337. hashes=None, # type: Optional[Hashes]
  338. ):
  339. # type: (...) -> CandidateEvaluator
  340. """Create a CandidateEvaluator object.
  341. :param target_python: The target Python interpreter to use when
  342. checking compatibility. If None (the default), a TargetPython
  343. object will be constructed from the running Python.
  344. :param specifier: An optional object implementing `filter`
  345. (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable
  346. versions.
  347. :param hashes: An optional collection of allowed hashes.
  348. """
  349. if target_python is None:
  350. target_python = TargetPython()
  351. if specifier is None:
  352. specifier = specifiers.SpecifierSet()
  353. supported_tags = target_python.get_tags()
  354. return cls(
  355. project_name=project_name,
  356. supported_tags=supported_tags,
  357. specifier=specifier,
  358. prefer_binary=prefer_binary,
  359. allow_all_prereleases=allow_all_prereleases,
  360. hashes=hashes,
  361. )
  362. def __init__(
  363. self,
  364. project_name, # type: str
  365. supported_tags, # type: List[Tag]
  366. specifier, # type: specifiers.BaseSpecifier
  367. prefer_binary=False, # type: bool
  368. allow_all_prereleases=False, # type: bool
  369. hashes=None, # type: Optional[Hashes]
  370. ):
  371. # type: (...) -> None
  372. """
  373. :param supported_tags: The PEP 425 tags supported by the target
  374. Python in order of preference (most preferred first).
  375. """
  376. self._allow_all_prereleases = allow_all_prereleases
  377. self._hashes = hashes
  378. self._prefer_binary = prefer_binary
  379. self._project_name = project_name
  380. self._specifier = specifier
  381. self._supported_tags = supported_tags
  382. def get_applicable_candidates(
  383. self,
  384. candidates, # type: List[InstallationCandidate]
  385. ):
  386. # type: (...) -> List[InstallationCandidate]
  387. """
  388. Return the applicable candidates from a list of candidates.
  389. """
  390. # Using None infers from the specifier instead.
  391. allow_prereleases = self._allow_all_prereleases or None
  392. specifier = self._specifier
  393. versions = {
  394. str(v) for v in specifier.filter(
  395. # We turn the version object into a str here because otherwise
  396. # when we're debundled but setuptools isn't, Python will see
  397. # packaging.version.Version and
  398. # pkg_resources._vendor.packaging.version.Version as different
  399. # types. This way we'll use a str as a common data interchange
  400. # format. If we stop using the pkg_resources provided specifier
  401. # and start using our own, we can drop the cast to str().
  402. (str(c.version) for c in candidates),
  403. prereleases=allow_prereleases,
  404. )
  405. }
  406. # Again, converting version to str to deal with debundling.
  407. applicable_candidates = [
  408. c for c in candidates if str(c.version) in versions
  409. ]
  410. filtered_applicable_candidates = filter_unallowed_hashes(
  411. candidates=applicable_candidates,
  412. hashes=self._hashes,
  413. project_name=self._project_name,
  414. )
  415. return sorted(filtered_applicable_candidates, key=self._sort_key)
  416. def _sort_key(self, candidate):
  417. # type: (InstallationCandidate) -> CandidateSortingKey
  418. """
  419. Function to pass as the `key` argument to a call to sorted() to sort
  420. InstallationCandidates by preference.
  421. Returns a tuple such that tuples sorting as greater using Python's
  422. default comparison operator are more preferred.
  423. The preference is as follows:
  424. First and foremost, candidates with allowed (matching) hashes are
  425. always preferred over candidates without matching hashes. This is
  426. because e.g. if the only candidate with an allowed hash is yanked,
  427. we still want to use that candidate.
  428. Second, excepting hash considerations, candidates that have been
  429. yanked (in the sense of PEP 592) are always less preferred than
  430. candidates that haven't been yanked. Then:
  431. If not finding wheels, they are sorted by version only.
  432. If finding wheels, then the sort order is by version, then:
  433. 1. existing installs
  434. 2. wheels ordered via Wheel.support_index_min(self._supported_tags)
  435. 3. source archives
  436. If prefer_binary was set, then all wheels are sorted above sources.
  437. Note: it was considered to embed this logic into the Link
  438. comparison operators, but then different sdist links
  439. with the same version, would have to be considered equal
  440. """
  441. valid_tags = self._supported_tags
  442. support_num = len(valid_tags)
  443. build_tag = () # type: BuildTag
  444. binary_preference = 0
  445. link = candidate.link
  446. if link.is_wheel:
  447. # can raise InvalidWheelFilename
  448. wheel = Wheel(link.filename)
  449. if not wheel.supported(valid_tags):
  450. raise UnsupportedWheel(
  451. "{} is not a supported wheel for this platform. It "
  452. "can't be sorted.".format(wheel.filename)
  453. )
  454. if self._prefer_binary:
  455. binary_preference = 1
  456. pri = -(wheel.support_index_min(valid_tags))
  457. if wheel.build_tag is not None:
  458. match = re.match(r'^(\d+)(.*)$', wheel.build_tag)
  459. build_tag_groups = match.groups()
  460. build_tag = (int(build_tag_groups[0]), build_tag_groups[1])
  461. else: # sdist
  462. pri = -(support_num)
  463. has_allowed_hash = int(link.is_hash_allowed(self._hashes))
  464. yank_value = -1 * int(link.is_yanked) # -1 for yanked.
  465. return (
  466. has_allowed_hash, yank_value, binary_preference, candidate.version,
  467. build_tag, pri,
  468. )
  469. def sort_best_candidate(
  470. self,
  471. candidates, # type: List[InstallationCandidate]
  472. ):
  473. # type: (...) -> Optional[InstallationCandidate]
  474. """
  475. Return the best candidate per the instance's sort order, or None if
  476. no candidate is acceptable.
  477. """
  478. if not candidates:
  479. return None
  480. best_candidate = max(candidates, key=self._sort_key)
  481. return best_candidate
  482. def compute_best_candidate(
  483. self,
  484. candidates, # type: List[InstallationCandidate]
  485. ):
  486. # type: (...) -> BestCandidateResult
  487. """
  488. Compute and return a `BestCandidateResult` instance.
  489. """
  490. applicable_candidates = self.get_applicable_candidates(candidates)
  491. best_candidate = self.sort_best_candidate(applicable_candidates)
  492. return BestCandidateResult(
  493. candidates,
  494. applicable_candidates=applicable_candidates,
  495. best_candidate=best_candidate,
  496. )
  497. class PackageFinder(object):
  498. """This finds packages.
  499. This is meant to match easy_install's technique for looking for
  500. packages, by reading pages and looking for appropriate links.
  501. """
  502. def __init__(
  503. self,
  504. link_collector, # type: LinkCollector
  505. target_python, # type: TargetPython
  506. allow_yanked, # type: bool
  507. format_control=None, # type: Optional[FormatControl]
  508. candidate_prefs=None, # type: CandidatePreferences
  509. ignore_requires_python=None, # type: Optional[bool]
  510. ):
  511. # type: (...) -> None
  512. """
  513. This constructor is primarily meant to be used by the create() class
  514. method and from tests.
  515. :param format_control: A FormatControl object, used to control
  516. the selection of source packages / binary packages when consulting
  517. the index and links.
  518. :param candidate_prefs: Options to use when creating a
  519. CandidateEvaluator object.
  520. """
  521. if candidate_prefs is None:
  522. candidate_prefs = CandidatePreferences()
  523. format_control = format_control or FormatControl(set(), set())
  524. self._allow_yanked = allow_yanked
  525. self._candidate_prefs = candidate_prefs
  526. self._ignore_requires_python = ignore_requires_python
  527. self._link_collector = link_collector
  528. self._target_python = target_python
  529. self.format_control = format_control
  530. # These are boring links that have already been logged somehow.
  531. self._logged_links = set() # type: Set[Link]
  532. # Don't include an allow_yanked default value to make sure each call
  533. # site considers whether yanked releases are allowed. This also causes
  534. # that decision to be made explicit in the calling code, which helps
  535. # people when reading the code.
  536. @classmethod
  537. def create(
  538. cls,
  539. link_collector, # type: LinkCollector
  540. selection_prefs, # type: SelectionPreferences
  541. target_python=None, # type: Optional[TargetPython]
  542. ):
  543. # type: (...) -> PackageFinder
  544. """Create a PackageFinder.
  545. :param selection_prefs: The candidate selection preferences, as a
  546. SelectionPreferences object.
  547. :param target_python: The target Python interpreter to use when
  548. checking compatibility. If None (the default), a TargetPython
  549. object will be constructed from the running Python.
  550. """
  551. if target_python is None:
  552. target_python = TargetPython()
  553. candidate_prefs = CandidatePreferences(
  554. prefer_binary=selection_prefs.prefer_binary,
  555. allow_all_prereleases=selection_prefs.allow_all_prereleases,
  556. )
  557. return cls(
  558. candidate_prefs=candidate_prefs,
  559. link_collector=link_collector,
  560. target_python=target_python,
  561. allow_yanked=selection_prefs.allow_yanked,
  562. format_control=selection_prefs.format_control,
  563. ignore_requires_python=selection_prefs.ignore_requires_python,
  564. )
  565. @property
  566. def target_python(self):
  567. # type: () -> TargetPython
  568. return self._target_python
  569. @property
  570. def search_scope(self):
  571. # type: () -> SearchScope
  572. return self._link_collector.search_scope
  573. @search_scope.setter
  574. def search_scope(self, search_scope):
  575. # type: (SearchScope) -> None
  576. self._link_collector.search_scope = search_scope
  577. @property
  578. def find_links(self):
  579. # type: () -> List[str]
  580. return self._link_collector.find_links
  581. @property
  582. def index_urls(self):
  583. # type: () -> List[str]
  584. return self.search_scope.index_urls
  585. @property
  586. def trusted_hosts(self):
  587. # type: () -> Iterable[str]
  588. for host_port in self._link_collector.session.pip_trusted_origins:
  589. yield build_netloc(*host_port)
  590. @property
  591. def allow_all_prereleases(self):
  592. # type: () -> bool
  593. return self._candidate_prefs.allow_all_prereleases
  594. def set_allow_all_prereleases(self):
  595. # type: () -> None
  596. self._candidate_prefs.allow_all_prereleases = True
  597. @property
  598. def prefer_binary(self):
  599. # type: () -> bool
  600. return self._candidate_prefs.prefer_binary
  601. def set_prefer_binary(self):
  602. # type: () -> None
  603. self._candidate_prefs.prefer_binary = True
  604. def make_link_evaluator(self, project_name):
  605. # type: (str) -> LinkEvaluator
  606. canonical_name = canonicalize_name(project_name)
  607. formats = self.format_control.get_allowed_formats(canonical_name)
  608. return LinkEvaluator(
  609. project_name=project_name,
  610. canonical_name=canonical_name,
  611. formats=formats,
  612. target_python=self._target_python,
  613. allow_yanked=self._allow_yanked,
  614. ignore_requires_python=self._ignore_requires_python,
  615. )
  616. def _sort_links(self, links):
  617. # type: (Iterable[Link]) -> List[Link]
  618. """
  619. Returns elements of links in order, non-egg links first, egg links
  620. second, while eliminating duplicates
  621. """
  622. eggs, no_eggs = [], []
  623. seen = set() # type: Set[Link]
  624. for link in links:
  625. if link not in seen:
  626. seen.add(link)
  627. if link.egg_fragment:
  628. eggs.append(link)
  629. else:
  630. no_eggs.append(link)
  631. return no_eggs + eggs
  632. def _log_skipped_link(self, link, reason):
  633. # type: (Link, Text) -> None
  634. if link not in self._logged_links:
  635. # Mark this as a unicode string to prevent "UnicodeEncodeError:
  636. # 'ascii' codec can't encode character" in Python 2 when
  637. # the reason contains non-ascii characters.
  638. # Also, put the link at the end so the reason is more visible
  639. # and because the link string is usually very long.
  640. logger.debug(u'Skipping link: %s: %s', reason, link)
  641. self._logged_links.add(link)
  642. def get_install_candidate(self, link_evaluator, link):
  643. # type: (LinkEvaluator, Link) -> Optional[InstallationCandidate]
  644. """
  645. If the link is a candidate for install, convert it to an
  646. InstallationCandidate and return it. Otherwise, return None.
  647. """
  648. is_candidate, result = link_evaluator.evaluate_link(link)
  649. if not is_candidate:
  650. if result:
  651. self._log_skipped_link(link, reason=result)
  652. return None
  653. return InstallationCandidate(
  654. name=link_evaluator.project_name,
  655. link=link,
  656. # Convert the Text result to str since InstallationCandidate
  657. # accepts str.
  658. version=str(result),
  659. )
  660. def evaluate_links(self, link_evaluator, links):
  661. # type: (LinkEvaluator, Iterable[Link]) -> List[InstallationCandidate]
  662. """
  663. Convert links that are candidates to InstallationCandidate objects.
  664. """
  665. candidates = []
  666. for link in self._sort_links(links):
  667. candidate = self.get_install_candidate(link_evaluator, link)
  668. if candidate is not None:
  669. candidates.append(candidate)
  670. return candidates
  671. def process_project_url(self, project_url, link_evaluator):
  672. # type: (Link, LinkEvaluator) -> List[InstallationCandidate]
  673. logger.debug(
  674. 'Fetching project page and analyzing links: %s', project_url,
  675. )
  676. html_page = self._link_collector.fetch_page(project_url)
  677. if html_page is None:
  678. return []
  679. page_links = list(parse_links(html_page))
  680. with indent_log():
  681. package_links = self.evaluate_links(
  682. link_evaluator,
  683. links=page_links,
  684. )
  685. return package_links
  686. def find_all_candidates(self, project_name):
  687. # type: (str) -> List[InstallationCandidate]
  688. """Find all available InstallationCandidate for project_name
  689. This checks index_urls and find_links.
  690. All versions found are returned as an InstallationCandidate list.
  691. See LinkEvaluator.evaluate_link() for details on which files
  692. are accepted.
  693. """
  694. collected_links = self._link_collector.collect_links(project_name)
  695. link_evaluator = self.make_link_evaluator(project_name)
  696. find_links_versions = self.evaluate_links(
  697. link_evaluator,
  698. links=collected_links.find_links,
  699. )
  700. page_versions = []
  701. for project_url in collected_links.project_urls:
  702. package_links = self.process_project_url(
  703. project_url, link_evaluator=link_evaluator,
  704. )
  705. page_versions.extend(package_links)
  706. file_versions = self.evaluate_links(
  707. link_evaluator,
  708. links=collected_links.files,
  709. )
  710. if file_versions:
  711. file_versions.sort(reverse=True)
  712. logger.debug(
  713. 'Local files found: %s',
  714. ', '.join([
  715. url_to_path(candidate.link.url)
  716. for candidate in file_versions
  717. ])
  718. )
  719. # This is an intentional priority ordering
  720. return file_versions + find_links_versions + page_versions
  721. def make_candidate_evaluator(
  722. self,
  723. project_name, # type: str
  724. specifier=None, # type: Optional[specifiers.BaseSpecifier]
  725. hashes=None, # type: Optional[Hashes]
  726. ):
  727. # type: (...) -> CandidateEvaluator
  728. """Create a CandidateEvaluator object to use.
  729. """
  730. candidate_prefs = self._candidate_prefs
  731. return CandidateEvaluator.create(
  732. project_name=project_name,
  733. target_python=self._target_python,
  734. prefer_binary=candidate_prefs.prefer_binary,
  735. allow_all_prereleases=candidate_prefs.allow_all_prereleases,
  736. specifier=specifier,
  737. hashes=hashes,
  738. )
  739. def find_best_candidate(
  740. self,
  741. project_name, # type: str
  742. specifier=None, # type: Optional[specifiers.BaseSpecifier]
  743. hashes=None, # type: Optional[Hashes]
  744. ):
  745. # type: (...) -> BestCandidateResult
  746. """Find matches for the given project and specifier.
  747. :param specifier: An optional object implementing `filter`
  748. (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable
  749. versions.
  750. :return: A `BestCandidateResult` instance.
  751. """
  752. candidates = self.find_all_candidates(project_name)
  753. candidate_evaluator = self.make_candidate_evaluator(
  754. project_name=project_name,
  755. specifier=specifier,
  756. hashes=hashes,
  757. )
  758. return candidate_evaluator.compute_best_candidate(candidates)
  759. def find_requirement(self, req, upgrade):
  760. # type: (InstallRequirement, bool) -> Optional[InstallationCandidate]
  761. """Try to find a Link matching req
  762. Expects req, an InstallRequirement and upgrade, a boolean
  763. Returns a InstallationCandidate if found,
  764. Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise
  765. """
  766. hashes = req.hashes(trust_internet=False)
  767. best_candidate_result = self.find_best_candidate(
  768. req.name, specifier=req.specifier, hashes=hashes,
  769. )
  770. best_candidate = best_candidate_result.best_candidate
  771. installed_version = None # type: Optional[_BaseVersion]
  772. if req.satisfied_by is not None:
  773. installed_version = parse_version(req.satisfied_by.version)
  774. def _format_versions(cand_iter):
  775. # type: (Iterable[InstallationCandidate]) -> str
  776. # This repeated parse_version and str() conversion is needed to
  777. # handle different vendoring sources from pip and pkg_resources.
  778. # If we stop using the pkg_resources provided specifier and start
  779. # using our own, we can drop the cast to str().
  780. return ", ".join(sorted(
  781. {str(c.version) for c in cand_iter},
  782. key=parse_version,
  783. )) or "none"
  784. if installed_version is None and best_candidate is None:
  785. logger.critical(
  786. 'Could not find a version that satisfies the requirement %s '
  787. '(from versions: %s)',
  788. req,
  789. _format_versions(best_candidate_result.iter_all()),
  790. )
  791. raise DistributionNotFound(
  792. 'No matching distribution found for {}'.format(
  793. req)
  794. )
  795. best_installed = False
  796. if installed_version and (
  797. best_candidate is None or
  798. best_candidate.version <= installed_version):
  799. best_installed = True
  800. if not upgrade and installed_version is not None:
  801. if best_installed:
  802. logger.debug(
  803. 'Existing installed version (%s) is most up-to-date and '
  804. 'satisfies requirement',
  805. installed_version,
  806. )
  807. else:
  808. logger.debug(
  809. 'Existing installed version (%s) satisfies requirement '
  810. '(most up-to-date version is %s)',
  811. installed_version,
  812. best_candidate.version,
  813. )
  814. return None
  815. if best_installed:
  816. # We have an existing version, and its the best version
  817. logger.debug(
  818. 'Installed version (%s) is most up-to-date (past versions: '
  819. '%s)',
  820. installed_version,
  821. _format_versions(best_candidate_result.iter_applicable()),
  822. )
  823. raise BestVersionAlreadyInstalled
  824. logger.debug(
  825. 'Using version %s (newest of versions: %s)',
  826. best_candidate.version,
  827. _format_versions(best_candidate_result.iter_applicable()),
  828. )
  829. return best_candidate
  830. def _find_name_version_sep(fragment, canonical_name):
  831. # type: (str, str) -> int
  832. """Find the separator's index based on the package's canonical name.
  833. :param fragment: A <package>+<version> filename "fragment" (stem) or
  834. egg fragment.
  835. :param canonical_name: The package's canonical name.
  836. This function is needed since the canonicalized name does not necessarily
  837. have the same length as the egg info's name part. An example::
  838. >>> fragment = 'foo__bar-1.0'
  839. >>> canonical_name = 'foo-bar'
  840. >>> _find_name_version_sep(fragment, canonical_name)
  841. 8
  842. """
  843. # Project name and version must be separated by one single dash. Find all
  844. # occurrences of dashes; if the string in front of it matches the canonical
  845. # name, this is the one separating the name and version parts.
  846. for i, c in enumerate(fragment):
  847. if c != "-":
  848. continue
  849. if canonicalize_name(fragment[:i]) == canonical_name:
  850. return i
  851. raise ValueError("{} does not match {}".format(fragment, canonical_name))
  852. def _extract_version_from_fragment(fragment, canonical_name):
  853. # type: (str, str) -> Optional[str]
  854. """Parse the version string from a <package>+<version> filename
  855. "fragment" (stem) or egg fragment.
  856. :param fragment: The string to parse. E.g. foo-2.1
  857. :param canonical_name: The canonicalized name of the package this
  858. belongs to.
  859. """
  860. try:
  861. version_start = _find_name_version_sep(fragment, canonical_name) + 1
  862. except ValueError:
  863. return None
  864. version = fragment[version_start:]
  865. if not version:
  866. return None
  867. return version